package com.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.common.R;
import com.reggie.common.ReggieConstants;
import com.reggie.common.ReggieContext;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private final static AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    private final static String[] URI_PATTERN = new String[]{
            "/employee/login",
            "/backend/**",
            "/front/**",
            "/user/sendMsg",
            "/user/login"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        boolean match = match(requestURI);
        if (match) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        Long id = (Long) httpServletRequest.getSession().getAttribute(ReggieConstants.EMP_SESSION_KEY);
        Long userId = (Long) httpServletRequest.getSession().getAttribute(ReggieConstants.USER_SESSION_KEY);
        if (userId != null) {
            ReggieContext.set(userId);
            filterChain.doFilter(servletRequest, servletResponse);
            ReggieContext.remove();
            return;
        }
        if (id != null) {
            ReggieContext.set(id);
            filterChain.doFilter(servletRequest, servletResponse);
            ReggieContext.remove();
            return;
        }
        httpServletResponse.getWriter().write(JSON.toJSONString(R.error(ReggieConstants.NOT_LOGIN_KEY)));
    }

    public boolean match(String url) {
        for (String s : URI_PATTERN) {
            if (ANT_PATH_MATCHER.match(s, url))
                return true;
        }
        return false;
    }
}
